package opn.srn.command.load;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Map;

import opn.srn.command.Command;
import opn.srn.command.load.parser.IParser;
import opn.srn.command.load.parser.stream.StringStream;
import opn.srn.common.IMessage;
import opn.srn.common.SimpleMessage;
import opn.srn.event.EventConstants;
import opn.srn.event.SimpleEvent;

public class LoadCommand extends Command {

	public static final String NAME = "load";

	String inFilename;
	IParser parser = null;

	public LoadCommand() {
		super(NAME);
	}

	/**
	 * Parameters are <br/>
	 * format - File format<br/>
	 * infile - Input filename
	 * 
	 */
	@Override
	public void load(Map<String, String> parameters) throws Exception {
		String format = parameters.get("format");
		if (format == null) {
			throw new Exception("format parameter missing for load command...");
		}

		inFilename = parameters.get("infile");
		if (inFilename == null) {
			throw new Exception("infile parameter missing for load command...");
		}

		parser = FormatHelper.load(format);
	}

	@Override
	public void execute() throws Exception {
		fireEvent(new SimpleEvent(this, EventConstants.CMD_START, parser.getFieldMetaDatas()));

		fireEvent(new SimpleEvent(this, EventConstants.EXEC_START, parser.getFieldMetaDatas()));

		BufferedReader reader = new BufferedReader(new FileReader(inFilename));
		try {
			String line;
			while ((line = reader.readLine()) != null) {
				IMessage message = new SimpleMessage();
				parser.parse(new StringStream(line), message);
				fireEvent(new SimpleEvent(this, EventConstants.CMD_DATA, message));
			}
		} finally {
			reader.close();
			fireEvent(new SimpleEvent(this, EventConstants.EXEC_FINISH, parser.getFieldMetaDatas()));

			fireEvent(new SimpleEvent(this, EventConstants.CMD_FINISH, parser.getFieldMetaDatas()));
		}
	}
}
